/**
 * @FileName: AddOrdersCmccService.java
 * @Author
 * @Description:
 * @Date 2016年2月1日 下午4:40:42
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.NetInOrder;
import cn.hpclub.server.util.CommonUtil;
import cn.hpclub.server.util.DrawImageUtil;
import cn.hpclub.server.util.SystemConfigUtil;

public class AddOrdersCmccService{
    private static final Logger        logger         = LoggerFactory.getLogger(AddOrdersCmccService.class);
    public static AddOrdersCmccService service        = new AddOrdersCmccService();

    // 图片地址前缀
    private String                     filePathPrefix = SystemConfigUtil.getSystemConfig().getUploadDir();
    private String                     imageExtension = ".jpg";
    private String                     fontSide       = "front_side";
    private String                     backSide       = "back_side";
    private String                     fontSideBgUrl  = "";
    private String                     backSideBgUrl  = "";
    private Font                       f              = new Font("华文细黑", Font.PLAIN, 14);
    private Font                       f1             = new Font("华文细黑", Font.PLAIN, 17);
    private Font                       f2             = new Font("华文细黑", Font.BOLD, 16);
    private Font                       f3             = new Font("方正黑体简体", Font.PLAIN, 14);

    /**
     * 
     * @Title: drawIDCardImage
     * @Description:TODO
     * @param r
     * @param sourceFilePath
     * @throws ImageFormatException
     * @throws IOException
     *             void
     */
    public void drawIDCardImage(NetInOrder r, String sourcePathPrefix) throws ImageFormatException, IOException{
        fontSideBgUrl = sourcePathPrefix + "//img//IDCard//" + "front_side_bg.jpg";
        backSideBgUrl = sourcePathPrefix + "//img//IDCard//" + "back_side_bg.jpg";

        String z_img = drawIDCardImage(r, true);
        String f_img = drawIDCardImage(r, false);
        r.set("z_img", z_img);
        r.set("f_img", f_img);
    }

    /**
     * 生成身份证图片
     * 
     * @param r
     * @return
     * @throws IOException
     * @throws ImageFormatException
     */
    private String drawIDCardImage(NetInOrder r, boolean isFront) throws ImageFormatException, IOException{
        String bgUrl = isFront ? fontSideBgUrl : backSideBgUrl;
        InputStream is = new FileInputStream(bgUrl);
        JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
        BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
        Graphics g = buffImg.getGraphics();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateString = simpleDateFormat.format(new Date());
        File imageDir = new File(filePathPrefix + SystemConfig.UPLOAD_IMAGE_IDCARD_DIR + dateString + File.separator
                + r.getStr(NetInOrder.IDCARD));
        String uuid = CommonUtil.getUUID();

        if(isFront){
            drawFrontSide(r, g);
        } else{
            drawBackSide(r, g);
        }

        g.dispose();

        // 保存数据到目标文件
        String fileName = isFront ? fontSide : backSide;
        if(!imageDir.exists()){
            imageDir.mkdirs();
        }

        String imgFileDir = imageDir + File.separator + fileName + "_" + uuid + imageExtension;

        OutputStream os = new FileOutputStream(imgFileDir);
        JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
        en.encode(buffImg);

        is.close();
        os.close();

        // String imgDBUrl = SystemConfig.UPLOAD_IMAGE_DIR + "IDCard/" +
        // dateString + "/" + r.getStr(NetInOrder.IDCARD)
        // + "/" + fileName + imageExtension;

        logger.debug("imgFileDir = " + imgFileDir);
        // logger.debug("imgDBUrl = " + imgDBUrl);//不需要保存

        return imgFileDir;
    }

    /**
     * @Title: drawFrontSide
     * @Description:画身份证正面图片
     * @param r
     * @param g
     * @return String
     */

    private void drawFrontSide(NetInOrder r, Graphics g){
        // 画头像图
        String headImgUrl = r.getStr(NetInOrder.HEAD_IMG);
        String headImgDir = StrKit.notBlank(headImgUrl) ? headImgUrl.replace("/upload", "") : headImgUrl;
        // System.out.println("headImgDir = " + headImgDir);
        DrawImageUtil.drawImageOnImage(headImgDir, g, 255, 45, 120, 140);

        // 画姓名
        DrawImageUtil.drawTextOnImage(r.getStr(NetInOrder.NAME), g, 80, 52, f1);

        // 画性别
        DrawImageUtil.drawTextOnImage(r.getStr(NetInOrder.SEX), g, 80, 82, f);

        // 画民族
        DrawImageUtil.drawTextOnImage(r.getStr(NetInOrder.NATION), g, 160, 82, f);

        // 画出生年月日
        drawBirthday(r.getStr(NetInOrder.BIRTHDAY), g);

        // 画地址
        drawAdrress(r.getStr(NetInOrder.ADDRESS), g);

        // 画身份证号码
        drawIDCardNumber(r.getStr(NetInOrder.IDCARD), g);
    }

    /**
     * @Title: drawIDCardNumber
     * @Description:画身份证号码
     * @param str
     * @param g
     *            void
     */

    private void drawIDCardNumber(String num, Graphics g){
        char[] numArr = num.toCharArray();
        for(int i = 0; i < numArr.length; i++){
            DrawImageUtil.drawTextOnImage(String.valueOf(numArr[i]), g, 140 + 12 * i, 220, f2);
        }
    }

    /**
     * @Title: drawAdrress
     * @Description:画地址
     * @param str
     * @param g
     *            void
     */
    private void drawAdrress(String address, Graphics g){
        if(!StrKit.isBlank(address)){
            int oneCount = 11;
            char[] addressArr = address.toCharArray();
            int count = addressArr.length % oneCount;
            int lineCount = count == 0 ? count : (addressArr.length / oneCount + 1);
            int index = 0;
            for(int k = 0; k < lineCount; k++){
                for(int m = 0; m < oneCount; m++){
                    if(index >= addressArr.length){
                        break;
                    }
                    DrawImageUtil.drawTextOnImage(String.valueOf(addressArr[index]), g, 80 + m * 15, 142 + 20 * k, f);
                    index++;
                }
            }
        }

    }

    /**
     * @Title: drawBirthday
     * @Description:画年月日
     * @param birthday
     * @param g
     *            void
     */
    private void drawBirthday(String birthday, Graphics g){
        // 格式化日期
        String[] birthdayArr = birthday.split("-");

        DrawImageUtil.drawTextOnImage(birthdayArr[0], g, 80, 112, f3);// 画年
        DrawImageUtil.drawTextOnImage(birthdayArr[1], g, 140, 112, f3);// 画月
        DrawImageUtil.drawTextOnImage(birthdayArr[2], g, 178, 112, f3);// 画日
    }

    /**
     * @Title: drawBackSide
     * @Description:画身份证背面图片
     * @param r
     * @param g
     *            void
     */
    private void drawBackSide(NetInOrder r, Graphics g){
        // 画签发机关
        DrawImageUtil.drawTextOnImage(r.getStr(NetInOrder.VISA_OFFICE), g, 160, 195, f);

        // 画有效期限
        DrawImageUtil.drawTextOnImage(r.getStr(NetInOrder.EXPIRE_DATE), g, 160, 226, f);
    }

    /**
     * @Title: drawIDCardImage
     * @Description:单元测试用
     * @param b
     * @return String
     * @throws IOException
     * @throws ImageFormatException
     * @throws FontFormatException
     */
    // public String drawIDCardImage(boolean isFront) throws
    // ImageFormatException, IOException{
    // String imagePathDir =
    // "E:\\WS\\WS_ALL\\dzg-server-admin\\src\\main\\WebRoot";
    // fontSideBgUrl = imagePathDir + "//img//IDCard//" + "front_side_bg.jpg";
    // backSideBgUrl = imagePathDir + "//img//IDCard//" + "back_side_bg.jpg";
    //
    // String bgUrl = isFront ? fontSideBgUrl : backSideBgUrl;
    // InputStream is = new FileInputStream(bgUrl);
    // JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
    // BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
    // Graphics g = buffImg.getGraphics();
    // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    // String dateString = simpleDateFormat.format(new Date());
    // File imageDir = new File(
    // imagePathDir + "/upload/image/IDCard/" + dateString + File.separator +
    // "510206198801012226");
    // String uuid = CommonUtil.getUUID();
    //
    // if(isFront){
    // String headImgUrl = imagePathDir + "/upload/image/headimg.jpg";
    // // 画头像图
    // DrawImageUtil.drawImageOnImage(headImgUrl, g, 255, 45, 120, 140);
    //
    // // 画姓名
    //
    // DrawImageUtil.drawTextOnImage("来测试", g, 80, 55, f1);
    //
    // // 画性别
    // DrawImageUtil.drawTextOnImage("女", g, 80, 82, f);
    //
    // // 画民族
    // DrawImageUtil.drawTextOnImage("汉", g, 160, 82, f);
    //
    // // 画出生年月日
    // String[] birthdayArr = "1988-12-31".split("-");
    //
    // DrawImageUtil.drawTextOnImage(birthdayArr[0], g, 80, 112, f3);// 画年
    // DrawImageUtil.drawTextOnImage(birthdayArr[1], g, 140, 112, f3);// 画月
    // DrawImageUtil.drawTextOnImage(birthdayArr[2], g, 178, 112, f3);// 画日
    //
    // String newAddress = "四川省双流县华阳锦江路四段111号10栋3单元206号";
    //
    // if(!StrKit.isBlank(newAddress)){
    // int oneCount = 11;
    // char[] newAddressArr = newAddress.toCharArray();
    // int count = newAddressArr.length % oneCount;
    // int lineCount = count == 0 ? count : (newAddressArr.length / oneCount +
    // 1);
    //
    // // logger.debug("lineCount = " + lineCount);
    // int index = 0;
    // for(int k = 0; k < lineCount; k++){
    // for(int m = 0; m < oneCount; m++){
    // if(index >= newAddressArr.length){
    // break;
    // }
    // DrawImageUtil.drawTextOnImage(newAddressArr[index] + "", g, 80 + m * 15,
    // 142 + 20 * k, f);
    // // logger.debug("oneLineAddr = " + newAddressArr[index] +
    // // "");
    // index++;
    // }
    //
    // }
    // }
    //
    // char[] numArr = "510206198801012226".toCharArray();
    // for(int ii = 0; ii < numArr.length; ii++){
    // DrawImageUtil.drawTextOnImage(String.valueOf(numArr[ii]), g, 140 + 12 *
    // ii, 220, f2);
    // }
    // } else{
    // // 画签发机关
    // DrawImageUtil.drawTextOnImage("双流县公安局", g, 160, 195, f);
    //
    // // 画有效期限
    // DrawImageUtil.drawTextOnImage("2012.05.26-2032.05.25", g, 160, 226, f);
    // }
    //
    // g.dispose();
    //
    // // 保存数据到目标文件
    // String fileName = isFront ? fontSide : backSide;
    // if(!imageDir.exists()){
    // imageDir.mkdirs();
    // }
    //
    // String imgFileDir = imageDir + File.separator + fileName + "_" + uuid +
    // imageExtension;
    //
    // OutputStream os = new FileOutputStream(imgFileDir);
    // JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
    // en.encode(buffImg);
    //
    // is.close();
    // os.close();
    //
    // // String imgDBUrl = SystemConfig.UPLOAD_IMAGE_DIR + "IDCard/" +
    // // dateString + "/" + r.getStr(NetInOrder.IDCARD)
    // // + "/" + fileName + imageExtension;
    //
    // logger.debug("imgFileDir = " + imgFileDir);
    // // logger.debug("imgDBUrl = " + imgDBUrl);//不需要保存
    //
    // // 删除身份证图片
    // // File imageFileDir = new File(imagePathDir + "/upload/image/IDCard/");
    // // if(deleteDir(imageFileDir)){
    // // System.out.println("delete IDCard images success");
    // // } else{
    // // System.out.println("delete IDCard images failure");
    // // }
    //
    // return imgFileDir;
    // }
    //
    // private boolean deleteDir(File dir){
    // if(dir.isDirectory()){
    // String[] children = dir.list();// 递归删除目录中的子目录下
    // for(int i = 0; i < children.length; i++){
    // boolean success = deleteDir(new File(dir, children[i]));
    // if(!success){
    // return false;
    // }
    // }
    // }
    // // 目录此时为空，可以删除
    // return dir.delete();
    // }
}
